package cn.shyouchi.wuguanjia.android.ui.event.train;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


@RuntimePermissions
public class AddTrainActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.edit_train_name)
    EditText mEditTrainName;
    @BindView(R.id.edit_train_content)
    EditText mEditTrainContent;
    @BindView(R.id.photo_snpl)
    BGASortableNinePhotoLayout mPhotoSnpl;
    ArrayList<String> photos = new ArrayList<>();


    EventApi mEventApi;
    String projectId;

    TrainEntity.ResultMessageBean entity;

    boolean isEdit;


    @Override
    public int initContentView() {
        return R.layout.activity_add_train;
    }

    @Override
    public void initInjector() {
        mEventApi = new EventApi(mContext);
        projectId = getIntent().getStringExtra("projectId");
        entity = getIntent().getParcelableExtra("train");
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        mPhotoSnpl.init(this);
        mPhotoSnpl.setDelegate(this);
        if (entity != null) {
            initEntity();
            isEdit = true;
        }


    }

    private void initEntity() {

        mEditTrainName.setText(entity.getTrainingname());
        mEditTrainContent.setText(entity.getTrainingcontent());
        mPhotoSnpl.setData((ArrayList<String>) entity.getImage());
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("保存");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("保存")) {
            generateEntityExit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void choicePhotoWrapper() {
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "TakePhoto");
        startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 3, null, true), REQUEST_CODE_CHOOSE_PHOTO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            photos.addAll(BGAPhotoPickerActivity.getSelectedImages(data));
            mPhotoSnpl.setData(photos);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            mPhotoSnpl.setData(BGAPhotoPickerActivity.getSelectedImages(data));
        }
    }

    private void generateEntityExit() {
        if (TextUtils.isEmpty(mEditTrainName.getText().toString())) {
            mEditTrainName.setError("标题不能空");
            return;
        }
//        if (TextUtils.isEmpty(mEditHandoverContent.getText().toString())) {
//            mEditHandoverContent.setError("内容不能空");
//            return;
//        }

        if (isEdit) {
            mEventApi.upTrain(projectId,
                    String.valueOf(entity.getId()),
                    mEditTrainName.getText().toString(),
                    mEditTrainContent.getText().toString(),
                    mPhotoSnpl.getData()).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult result) {
                            EventBus.getDefault().post(new DataChangeEvent());
                            finish();
                        }
                    });
        } else {
            mEventApi.addTrain(projectId, mEditTrainName.getText().toString(),
                    mEditTrainContent.getText().toString(),
                    mPhotoSnpl.getData()).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult result) {
                            setResult(EventTrainActivity.REQUEST_TYPE_ADD_SUCCESS);
                            finish();
                        }
                    });
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        AddTrainActivityPermissionsDispatcher.choicePhotoWrapperWithCheck(this);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotoSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, mPhotoSnpl.getMaxItemCount(), models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        AddTrainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
